//
//  MOFoodOrderListViewController.m
//  MobileOffice
//
//  Created by 晓 on 2019/10/15.
//  Copyright © 2019 com.idolmedia. All rights reserved.
//

#import "MOFoodOrderListViewController.h"
#import "MOFoodOrderListCell.h"
#import "MOFoodOrderListDetailViewController.h"
#import "MORefreshNormalHeader.h"
#import "MORefreshGifFooter.h"
#import "MOFoodOrderListCell.h"

@interface MOFoodOrderListViewController ()<UITableViewDelegate,UITableViewDataSource,YPSwipeTableViewCellDelegate>

@property(nonatomic,strong) UITableView *tableView;

@property(nonatomic,strong) NSMutableArray *buttonArray;

@property(nonatomic,strong)NSMutableArray *dataArray;

@property(nonatomic,assign)NSInteger currentPage;


@end

@implementation MOFoodOrderListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"订单";
    self.view.backgroundColor = KWhiteColor;
    [self.view addSubview:self.tableView];
}


-(void)getData
{
    NSString *postUrl = [NSString stringWithFormat:@"%@?authorization=%@",GETORDERS,[NSString URLEncodedString:[MOUser sharedMOUser].token]];
    NSDictionary *dic = @{
                          @"createUser":[MOUser sharedMOUser].userName,
                          @"pageNo":[NSString stringWithFormat:@"%ld",(long)self.currentPage],
                          @"limit":@"10"
                          };
    [PPNetworkHelper POST:postUrl parameters:dic success:^(id responseObject) {
        NSLog(@"订单列表：%@",responseObject);
        
        if (self.currentPage==1) {
            self.dataArray = [NSMutableArray array];
        }
        NSArray *dataArray = [NSArray array];
        if ([responseObject isKindOfClass:[NSArray class]]) {
            dataArray = responseObject;
            for (int i = 0; i<dataArray.count; i++) {
                MOFoodOrderListModel *model = [[MOFoodOrderListModel alloc]init];
                model.status = dataArray[i][@"status"];
                model.amount = dataArray[i][@"amount"];
                model.recipeTime = dataArray[i][@"recipeTime"];
                model.details = dataArray[i][@"details"];
                model.mealTimeCategory = dataArray[i][@"mealTimeCategory"];
                model.restaurantName = dataArray[i][@"restaurantName"];
                model.createTime = dataArray[i][@"createTime"];
                model.orderId = dataArray[i][@"orderId"];
                model.restaurantId = dataArray[i][@"restaurantId"];
                [self.dataArray addObject:model];
            }
        }
        
        if (dataArray.count==0) {
            [self.tableView.mj_footer endRefreshingWithNoMoreData];
            [[ADShowMessage shareShowMessage] showTextOnly:@"暂无数据" showInView:self.view];
        }
        [self refreshEnding];
    } failure:^(NSError *error) {
        NSLog(@"订单列表：%@",[error localizedDescription]);
        [self refreshEnding];
        [[ADShowMessage shareShowMessage] showTextOnly:[error localizedDescription] showInView:self.view];
    }];
}

#pragma mark -刷新，加载更多
//刷新
- (void)downloadAfaterDataSource{
    self.currentPage = 1;
    [self getData];
}

//加载更多
- (void)downloadBeforeDataSource{
    self.currentPage++;
    [self getData];
}

//刷新效果停止
- (void)refreshEnding{
    [self.tableView.mj_footer endRefreshing];
    [self.tableView.mj_header endRefreshing];
    [self.tableView reloadData];
}

#pragma mark - UITableViewDelegate,UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return self.dataArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *cellIdentifier = @"Cell";
    MOFoodOrderListCell *foodOrderListCell = [[MOFoodOrderListCell alloc]cellCreat:cellIdentifier AndArray:self.buttonArray andTableView:tableView cellIndexPath:indexPath andType:0];
    foodOrderListCell.delegate = self;
    foodOrderListCell.model = self.dataArray[indexPath.section];
    return foodOrderListCell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 80;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 10;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.00000001;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    return nil;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    return nil;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
}

#pragma mark - YPSwipeTableViewCelldidSelectBtnWithTag 代理
- (void)YPSwipeTableViewCelldidSelectBtnWithTag:(NSInteger)tag andIndexPath:(NSIndexPath *)indexpath{
    
    MOFoodOrderListModel *model = self.dataArray[indexpath.section];
    if (tag==1) {
        MOFoodOrderListDetailViewController *vc = [[MOFoodOrderListDetailViewController alloc]init];
        vc.model = model;
        [self.navigationController pushViewController:vc animated:YES];
    }else{
        
        if ([model.status integerValue]==1) {
            [[ADShowMessage shareShowMessage]showTextOnly:@"该订单已取消，不能重复取消！" showInView:self.view];
            return;
        }else{
            MOHintView *hintView = [[MOHintView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT) andContentStr:@"确定取消该订单？"];
            __weak typeof (self)weakSelf = self;
            hintView.clickSureButtonBlock = ^{
                [weakSelf cancelOrderAndOrderId:model.restaurantId orderId:model.orderId time:model.recipeTime type:model.mealTimeCategory];
            };
            [WINDOW addSubview:hintView];
        }
    }

}

-(void)cancelOrderAndOrderId:(NSString *)restaurantId orderId:(NSString *)orderId time:(NSString *)time type:(NSString *)type{
    
    NSString *postUrl = [NSString stringWithFormat:@"%@?authorization=%@",CHECKCANDO,[NSString URLEncodedString:[MOUser sharedMOUser].token]];
    NSDictionary *dic = @{
                          @"restaurantId":restaurantId,
                          @"dateTime":time,
                          @"type":@"cancel"
                          };
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [PPNetworkHelper POST:postUrl parameters:dic success:^(id responseObject) {
        NSLog(@"查询可否取消订单：%@",responseObject);
        
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            NSDictionary *dataDic = responseObject;
            NSArray *allKeysArr = dataDic.allKeys;
            NSInteger can = 0;
            for (int i = 0; i<allKeysArr.count; i++) {
                NSString *t = [allKeysArr[i] substringToIndex:1];
                if ([t integerValue]==[type integerValue]&&[dataDic[allKeysArr[i]] integerValue]==1) {
                    can = 1;
                }
            }
            if (can==1) {
                [self getCancelOrderDataAndOrderId:orderId];
            }else{
                [MBProgressHUD hideHUDForView:self.view animated:YES];
                [[ADShowMessage shareShowMessage]showTextOnly:@"该订单已经超过取消时段，不能取消!" showInView:self.view];
            }
        }else{
            [[ADShowMessage shareShowMessage]showTextOnly:@"取消失败，稍后重试" showInView:self.view];
            [MBProgressHUD hideHUDForView:self.view animated:YES];
        }
    } failure:^(NSError *error) {
        NSLog(@"查询可否取消订单：%@",[error localizedDescription]);
        [MBProgressHUD hideHUDForView:self.view animated:YES];
    }];
}

-(void)getCancelOrderDataAndOrderId:(NSString *)orderId
{
    NSString *postUrl = [NSString stringWithFormat:@"%@?authorization=%@",DELORDER,[NSString URLEncodedString:[MOUser sharedMOUser].token]];
    NSDictionary *dic = @{
                          @"orderId":orderId
                          };
    [PPNetworkHelper POST:postUrl parameters:dic success:^(id responseObject) {
        NSLog(@"取消订单：%@",responseObject);
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            [[ADShowMessage shareShowMessage]showTextOnly:responseObject[@"msg"] showInView:self.view];
            [self downloadAfaterDataSource];
        }
    } failure:^(NSError *error) {
        NSLog(@"取消订单：%@",[error localizedDescription]);
        [MBProgressHUD hideHUDForView:self.view animated:YES];
    }];
}

#pragma mark -懒加载
- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - StatusBarAndNavigationBarHeight) style:UITableViewStyleGrouped];
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.backgroundColor = KGrayColor_f8f8f8;
        
        _tableView.mj_header = [MORefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(downloadAfaterDataSource)];
        _tableView.mj_footer = [MORefreshGifFooter footerWithRefreshingTarget:self refreshingAction:@selector(downloadBeforeDataSource)];
        [_tableView.mj_header beginRefreshing];
    }
    return _tableView;
}


-(NSMutableArray *)buttonArray
{
    
    UIButton *btn11 = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 70, 80)];
    btn11.backgroundColor = [UIColor whiteColor];
    [btn11 setTitle:@"订单详情" forState:UIControlStateNormal];
    [btn11 setTitleColor:KBlueColor_2C94FF forState:UIControlStateNormal];
    [btn11 setImage:[UIImage imageNamed:@"dingcan_detail"] forState:UIControlStateNormal];
    btn11.titleLabel.font = FONT_SIZE(12);
    btn11.userInteractionEnabled = NO;
    [btn11 SG_imagePositionStyle:(SGImagePositionStyleTop) spacing:5];

    UIButton *btn22 = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 70, 80)];
    btn22.backgroundColor = [UIColor redColor];
    [btn22 setTitle:@"取消订单" forState:UIControlStateNormal];
    [btn22 setImage:[UIImage imageNamed:@"dingcan_delete"] forState:UIControlStateNormal];
    btn22.titleLabel.font = FONT_SIZE(12);
    btn22.userInteractionEnabled = NO;
    [btn22 SG_imagePositionStyle:(SGImagePositionStyleTop) spacing:5];
    
    UIButton *btn2 = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 80, 80)];
    btn2.backgroundColor = KGrayColor_f8f8f8;
    [btn2 addSubview:btn22];
    
    UIButton *btn1 = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 80, 80)];
    btn1.backgroundColor = KGrayColor_f8f8f8;
    [btn1 addSubview:btn11];
    
    _buttonArray = [[NSMutableArray alloc]initWithObjects:btn2,btn1, nil];
    
    return _buttonArray;
}


@end
